<?php
class Model{
	public $table;
	public $error;
	public $opt=array(
		'filed'=>' * ',
		'where'=>'',
		'group'=>'',
		'having'=>'',
		'order'=>'',
		'limit'=>'',
	);

	public function __construct($table=null){
		if($table)$this->table=$table;
			//连接数据库
		if(!@mysql_connect(C('DB_HOST'),C('DB_USER'),C('DB_PASSWORD'))){
			die('连接数据库失败');
			// die(mysql_error());
		}
		//设置字符编码
		mysql_query('set names '.C('DB_CHARSET'));
		//选择数据库
		if(!@mysql_select_db(C('DB_NAME'))){
			die('选择数据库失败');
		}
	}
	// 取一条数据
	public function find(){
		$data=$this->select();
		return $data?current($data):$data;
	}
	//字段
	public function filed($filed){
		$this->opt['filed']=$filed;
		return $this;
	}

	//条件
	public function where($where){
		$this->opt['where']=' where '.$where;
		return $this;
	}
	//分组
	public function group($group){
		$this->opt['group']=' group by '.$group;
		return $this;
	}
	//筛选
	public function having($having){
		$this->opt['having']=' having '.$having;
		return $this;
	}
	//排序
	public function order($order){
		$this->opt['order']=' order by '.$order;
		return $this;
	}
	//截取
	public function limit($limit){
		$this->opt['limit']=' limit '.$limit;
		return $this;
	}
	//查询操作

	public function select(){
		$sql="select {$this->opt['filed']} from ".$this->table.$this->opt['where'].
		$this->opt['group'].$this->opt['having'].$this->opt['order'].$this->opt['limit'];
		return $this->query($sql);
	}
	//删除
	public function delete(){
		if(empty($this->opt['where']))return false;
		$sql='delete from '.$this->table.$this->opt['where'].$this->opt['order'].$this->opt['limit'];
		return $this->exe($sql);
	}
	//插入
	public function insert($data){
		$sql='insert into '.$this->table;
		$keys=array_keys($data);
		$values=array_values($data);
		foreach($values as $k=>$v){
			$values[$k]=addslashes($v);
		}
		$sql.=" (".implode(',',$keys).")"." values('".implode("','", $values)."')";
		return $this->exe($sql);
	}
	//修改
	public function update($data){
		if(empty($this->opt['where']))return false;
		$sql='update '.$this->table.' set ';
		foreach($data as $k=>$v){
			$data[$k]=addslashes($v);
		}
		foreach($data as $name=>$value){
			$sql.=$name.'="'.$value.'",';
		}
		$sql=substr($sql, 0,-1).$this->opt['where'];
		return $this->exe($sql);
	}
	//执行增、删、改、语句
	function exe($sql){
		$statu=mysql_query($sql);
		if($statu){
			$insertId=mysql_insert_id();
			return $insertId?$insertId:true;
		}else{
			die(mysql_error());
		}
	}

	//执行查询语句
	public function query($sql){
		$result=mysql_query($sql);
		if($result){
			$data=array();
			while($row=mysql_fetch_assoc($result)){
				$data[]=$row;
			}
			return $data;
		}else{
			die(mysql_error());
		}
	}
}
?>